package com.cn.xiongmeng.czlxz;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.anythink.banner.api.ATBannerListener;
import com.anythink.banner.api.ATBannerView;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATNetworkConfirmInfo;
import com.anythink.core.api.ATSDK;
import com.anythink.core.api.AdError;
import com.anythink.interstitial.api.ATInterstitial;
import com.anythink.interstitial.api.ATInterstitialListener;
import com.anythink.rewardvideo.api.ATRewardVideoAd;
import com.anythink.rewardvideo.api.ATRewardVideoListener;
import com.anythink.splashad.api.ATSplashAd;
import com.anythink.splashad.api.ATSplashAdExtraInfo;
import com.anythink.splashad.api.ATSplashExListener;
import com.cn.xiongmeng.czlxz.activity.WorkActivity;
import com.cn.xiongmeng.czlxz.taku.RewardVideoAd;

public class MainApplication extends Application {
    private final String TAG = "MainApplication";
    private ATSplashAd splashAd; // 开屏
    private ATBannerView mBannerView; // Banner
    private ATInterstitial mInterstitialAd; // 插屏
    private ATRewardVideoAd mRewardVideoAd; // 激励视频
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate.");
        initTakuSDK();
        // initSplashAd(); // 在Activity中调用（测试完毕）
        // initBannerView(); // 在Activity中调用，为了在关闭回调函数再调用load（测试完毕，只需要设计：不同activity如何共享banner）
        // initInterstitialAd(); // 需要在Activity中调用（测试完毕，只需要设计：什么时候弹出插屏广告）
    }
    // taku SDK初始化
    private void initTakuSDK(){
        // 测试模式
        //ATSDK.setNetworkLogDebug(true); // SDK日志开关
        //ATSDK.integrationChecking(getApplicationContext()); //根据输出的日志，检查各个广告平台的SDK集成是否正常
        // ATSDK.setDebuggerConfig(getApplicationContext(), "539d847e2feb6a6f", new ATDebuggerConfig.Builder(Adx_NETWORK).build());
        // ATSDK.setDebuggerConfig(getApplicationContext(), "539d847e2feb6a6f",new ATDebuggerConfig.Builder(GDT_NETWORK).build());
        //String TakuAppID = "a62b013be01931"; // 测试
        //String TakuAppKey = "c3d0d2a9a9d451b07e62b509659f7c97";

        String TakuAppID = "a678201a2df318"; // 错字来寻找
        String TakuAppKey = "a08bc87cafc4d453980e22951b372003d";
        ATSDK.init(getApplicationContext(), TakuAppID, TakuAppKey);//初始化SDK
        ATSDK.start();
    }
    public void initSplashAd(MainActivity activity){
        /* 百度、穿山甲需要特殊配置 */
        // 1、设置开屏广告的广告位id
        //String placementId = "b6791074586286"; // 测试
        String placementId = "b678203cb9f55c";
        // 2、初始化开屏广告的监听对象
        ATSplashExListener listener = new ATSplashExListener() {

            @Override
            public void onAdLoaded(boolean isTimeout) {
                Log.d(TAG, "onAdLoaded: 开屏广告,加载成功" );
                // activity.jumpToNextActivity();
            }

            @Override
            public void onAdLoadTimeout() {
                Log.d(TAG, "onAdLoadTimeout: 开屏广告,加载超时");
                activity.jumpToNextActivity();
            }

            @Override
            public void onNoAdError(AdError adError) {
                Log.e(TAG, "onBannerFailed:" + adError.getFullErrorInfo());
                activity.jumpToNextActivity();
            }

            @Override
            public void onAdShow(ATAdInfo atAdInfo) {
                Log.d(TAG, "onAdLoadTimeout: 开屏广告,展示");
            }

            @Override
            public void onAdClick(ATAdInfo atAdInfo) {
                Log.d(TAG, "onAdLoadTimeout: 开屏广告,点击");
            }

            @Override
            public void onAdDismiss(ATAdInfo atAdInfo, ATSplashAdExtraInfo splashAdExtraInfo) {
                Log.d(TAG, "onAdDismiss: 开屏广告,关闭");
                // Log.d(TAG, "onAdDismiss: " + splashAdExtraInfo.getDismissType());
                activity.jumpToNextActivity();
            }

            @Override
            public void onDeeplinkCallback(ATAdInfo atAdInfo, boolean isSuccess) {
                // deeplink回调，针对Adx、OnlineApi广告
                Log.d(TAG, "onDeeplinkCallback: 开屏广告,点击deeplink");
            }

            @Override
            public void onDownloadConfirm(Context context, ATAdInfo atAdInfo, ATNetworkConfirmInfo atNetworkConfirmInfo) {
                // 应用类广告点击下载时回调方法
                Log.d(TAG, "onDownloadConfirm: 开屏广告,点击下载");
            }
        };

        splashAd = new ATSplashAd(activity, placementId, listener, 5000);
        splashAd.loadAd(); // 发起加载
    }
    public void initBannerView(Activity activity){
        mBannerView = new ATBannerView(this);
        // 1、设置Banner的广告位id，其中bannerTakuPlacementID是通过Taku后台创建banner广告位获取的。（必须设置）
        // String bannerTakuPlacementID = "b679104826898f"; // 测试Banner广告位
        String bannerTakuPlacementID = "b678203fb57015"; // 错字来寻找
        mBannerView.setPlacementId(bannerTakuPlacementID);
        // 2、设置Banner视图的宽、高
        float ratio = 320/50f;//必须跟Taku后台配置的Banner广告源宽高比例一致，假设尺寸为320x50
        int width = getResources().getDisplayMetrics().widthPixels;//定一个宽度值，比如屏幕宽度
        int height = (int) (width / ratio);
        mBannerView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        // 2、为Banner设置监听
        mBannerView.setBannerAdListener(new ATBannerListener() {
            @Override
            public void onBannerLoaded() { // Banner加载成功回调
                Log.d(TAG, "onBannerLoaded: Banner,加载成功");
            }

            @Override
            public void onBannerFailed(AdError adError) { // Banner加载失败回调
                //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
                //AdError，请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                Log.e(TAG, "onBannerFailed:" + adError.getFullErrorInfo());
            }
            @Override
            public void onBannerShow(ATAdInfo atAdInfo) { // Banner展示回调
                //ATAdInfo可区分广告平台以及获取广告平台的广告位ID等
                //请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_sdk_callback_access?id=callback_info
                Log.d(TAG, "onBannerShow: Banner,展示");
                Log.d(TAG, "onBannerShow: 广告平台为：" + atAdInfo.getNetworkName());
                Log.d(TAG, "onBannerShow: ecpmLevel为：" + atAdInfo.getEcpmLevel());
                Log.d(TAG, "onBannerShow: ecpm为：" + atAdInfo.getEcpm());
            }

            @Override
            public void onBannerClicked(ATAdInfo atAdInfo) { // Banner点击回调
                Log.d(TAG, "onBannerClicked: Banner,点击");
            }

            @Override
            public void onBannerClose(ATAdInfo atAdInfo) { //Banner关闭回调（部分广告平台有该回调）
                Log.d(TAG, "onBannerClose: Banner,关闭");
                FrameLayout bannerViewContainer = (FrameLayout)(mBannerView.getParent());
                if (mBannerView != null && mBannerView.getParent() != null) {
                    ((ViewGroup) mBannerView.getParent()).removeView(mBannerView);
                }
                // 用户关闭banner，5秒钟后，再度加载、展示（貌似展示的时候是自动刷新回调）
                new Thread(new Runnable(){
                    @Override
                    public void run(){
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                                        ViewGroup.LayoutParams.WRAP_CONTENT,
                                        ViewGroup.LayoutParams.WRAP_CONTENT);
                                layoutParams.gravity = Gravity.CENTER;
                                bannerViewContainer.addView(mBannerView, layoutParams);
                                mBannerView.loadAd();
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onBannerAutoRefreshed(ATAdInfo atAdInfo) { //Banner自动刷新回调adsource_price
                Log.d(TAG, "onBannerAutoRefreshed: Banner自动刷新，平台为：" + atAdInfo);
            }

            @Override
            public void onBannerAutoRefreshFail(AdError adError) { //Banner自动刷新失败回调
                //AdError：https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                Log.e(TAG, "onBannerAutoRefreshFail:" + adError.getFullErrorInfo());
            }
        });
    }
    public void initInterstitialAd(Activity activity){ /* 插屏广告初始化函数，要保证传入的是activity */
        if (mInterstitialAd == null) {
            // String interstitialTakuPlacementID = "b62b014563dc89"; // 测试插屏广告位all（广告位关闭）
            // String interstitialTakuPlacementID = "b679107529b409"; // 测试插屏广告位
            String interstitialTakuPlacementID = "b678b545ad607e"; // 错字来寻找插屏广告位
            mInterstitialAd = new ATInterstitial(activity, interstitialTakuPlacementID);
            mInterstitialAd.setAdListener(new ATInterstitialListener() { // 插屏广告，加载成功回调
                @Override
                public void onInterstitialAdLoaded() {
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,加载成功");
                }

                @Override
                public void onInterstitialAdLoadFail(AdError adError) { // 插屏广告，加载失败回调
                    //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
                    //AdError，请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                    Log.e(TAG, "onInterstitialAdLoadFail:" + adError.getFullErrorInfo());
                }

                @Override
                public void onInterstitialAdClicked(ATAdInfo atAdInfo) { // 插屏广告，点击回调
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,点击");
                }

                @Override
                public void onInterstitialAdShow(ATAdInfo atAdInfo) { // 插屏广告，展示回调
                    //ATAdInfo可区分广告平台以及获取广告平台的广告位ID等
                    //请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_sdk_callback_access?id=callback_info
                    // 广告展示回调 建议在此回调中调用load进行广告的加载，方便下一次广告的展示
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,展示");
                    mInterstitialAd.load();
                }

                @Override
                public void onInterstitialAdClose(ATAdInfo atAdInfo) { // 插屏广告，关闭回调
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,关闭");
                }

                @Override
                public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) { // 插屏广告，视频广告开始播放回调
                    // 建议在此回调中调用load进行广告的加载，方便下一次广告的展示（不需要调用isAdReady()）
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,视频广告开始播放");
                    mInterstitialAd.load();
                }

                @Override
                public void onInterstitialAdVideoEnd(ATAdInfo atAdInfo) { // 插屏广告，视频广告播放结束回调
                    Log.d(TAG, "onInterstitialAdLoaded: 插屏广告,视频广告播放结束");
                }

                @Override
                public void onInterstitialAdVideoError(AdError adError) { // 插屏广告，视频广告播放出错回调
                    //AdError，请参考 https://docs.takuad.com/#/zh-cn/android/android_doc/android_test?id=aderror
                    Log.e(TAG, "onInterstitialAdVideoError:" + adError.getFullErrorInfo());
                }
            });
        }
        mInterstitialAd.load(); // 预加载
    }
    public void initRewardVideoAd(Activity activity){
        // 1、设置激励视频广告的广告位id
        // String rewardTakuPlacementID = "b6791076320372"; // 测试激励视频广告位
        String rewardTakuPlacementID = "b678bba40d6aae";
        if (mRewardVideoAd == null) {
            mRewardVideoAd = new ATRewardVideoAd(activity, rewardTakuPlacementID);
            mRewardVideoAd.setAdListener(new ATRewardVideoListener() {
                @Override
                public void onRewardedVideoAdLoaded() {
                    Log.d(TAG, "onRewardedVideoAdLoaded: 激励视频广告,加载成功");
                }

                @Override
                public void onRewardedVideoAdFailed(AdError adError) {
                    Log.e(TAG, "onRewardedVideoAdFailed:" + adError.getFullErrorInfo());
                }

                @Override
                public void onRewardedVideoAdPlayStart(ATAdInfo atAdInfo) {
                    // 激励视频展示
                    Log.d(TAG, "onRewardedVideoAdPlayStart: 激励视频广告,开始播放");
                    mRewardVideoAd.load();
                }

                @Override
                public void onRewardedVideoAdPlayEnd(ATAdInfo atAdInfo) {
                    Log.d(TAG, "onRewardedVideoAdPlayEnd: 激励视频广告,播放结束");
                }

                @Override
                public void onRewardedVideoAdPlayFailed(AdError adError, ATAdInfo atAdInfo) {
                    Log.d(TAG, "onRewardedVideoAdPlayFailed: 激励视频广告,播放出错");
                }

                @Override
                public void onRewardedVideoAdClosed(ATAdInfo atAdInfo) {
                    // 1、未播放完关闭，会调用
                    // 2、播放完关闭，会调用
                    Log.d(TAG, "onRewardedVideoAdClosed: 激励视频广告,被关闭");
                }

                @Override
                public void onRewardedVideoAdPlayClicked(ATAdInfo atAdInfo) {
                    Log.d(TAG, "onRewardedVideoAdPlayClicked: 激励视频广告,点击");
                }

                @Override
                public void onReward(ATAdInfo atAdInfo) {
                    //建议在此回调中下发奖励，一般在onRewardedVideoAdClosed之前回调
                    Log.d(TAG, "onReward: 激励视频广告,奖励发放");
                    Log.d(TAG, "onReward: ATAdInfo为: " + atAdInfo);
                    WorkActivity wordActivity = WorkActivity.getInstance();
                    if (wordActivity != null) {
                        // 使用indexActivity
                        RewardVideoAd.onReward(wordActivity, atAdInfo.getNetworkName(), atAdInfo.getEcpmLevel() , atAdInfo.getEcpm());
                    }
                }
            });
        }
        // 服务端激励回调（可选）
        /*String userid = "test_userid_001";
        String userdata = "test_userdata_001";
        Map localMap = new HashMap<>();
        localMap.put(ATAdConst.KEY.USER_ID, userid);
        localMap.put(ATAdConst.KEY.USER_CUSTOM_DATA, userdata);
        mRewardVideoAd.setLocalExtra(localMap);*/ //Load时传自定义参数，在广告源填充之后自定义参数会保存起来，在展示时回传。适用场景:传入会话信息做防作弊类似

        mRewardVideoAd.load();
    }
    public ATSplashAd getSplashAd(){
        return splashAd;
    }
    public ATBannerView getBannerView(){
        return mBannerView;
    }
    public ATInterstitial getInterstitialAd(){
        return mInterstitialAd;
    }
    public ATRewardVideoAd getRewardVideoAd(){
        return mRewardVideoAd;
    }
}
